import { login, getUserInfoApi, getBaseUserInfoApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import imghead from '@/assets/common/head.jpg'
const state = {
  token: getToken() || null,
  userInfo: {}
}

const mutations = {
  setToken(state, palylod) {
    state.token = palylod
    setToken(palylod)
  },
  setUserInfo(state, palylod) {
    state.userInfo = palylod
  },
  clearToken(state) {
    state.token = ''
    removeToken()
  },
  clearUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(context, value) {
    const res = await login(value)
    // 存取token
    const newToken = res.data
    context.commit('setToken', newToken)
    return res
  },
  async getUserinfo(context) {
    const res = await getUserInfoApi()
    const res2 = await getBaseUserInfoApi(res.data.userId)
    console.log(imghead)
    // res2.data.staffPhoto = 'https://img1.baidu.com/it/u=1550126854,340579180&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200'
    const baseData = {
      ...res.data,
      ...res2.data
    }
    context.commit('setUserInfo', baseData)
    console.log('获取用户信息成功', res)
    console.log('获取用户头像', res2)
    return baseData
  },
  // 在真实的开发场景中  退出要调用后端接口 同步前后的token信息
  LoginOut({ commit }) {
    commit('clearToken')
    commit('clearUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
